<template>
	<view class="page-container">
		<!-- <cu-custom bgColor="bg-white" :isBack="false">
			<template v-slot:content>
				<view class="text-bold text-black">购物车</view>
			</template>
			
		</cu-custom> -->

		<!-- 如果购物车为空 -->
		<view v-if="!merchantCarts || merchantCarts.length === 0" class="empty-cart">
			<text class="cuIcon-cart text-gray" style="font-size: 100rpx;"></text>
			<view class="text-gray margin-top-sm">购物车还是空的</view>
			<button class="cu-btn bg-red margin-top-lg round" @click="goToHome">去逛逛</button>
		</view>

		<!-- 购物车列表 -->
		<view v-else class="cart-list">
			<!-- 按商家遍历 -->
			<view class="merchant-card" v-for="(merchantCart, mIndex) in merchantCarts" :key="merchantCart.merchantId">
				<!-- 商家信息 -->
				<view class="merchant-header">
					<checkbox :checked="merchantCart.checked" @click="toggleShopCheck(mIndex)"></checkbox>
					<view class="text-bold text-lg margin-left-sm">{{ merchantCart.merchantName }}</view>
					<text class="cuIcon-right margin-left-xs"></text>
				</view>

				<!-- 商品列表 -->
				<view class="goods-list">
					<view class="goods-item" 
						v-for="(item, gIndex) in merchantCart.cartItems" 
						:key="item.goodId"
						@longpress="handleLongPress(mIndex, gIndex)">
						
						<checkbox :checked="item.checked" @click="toggleGoodsCheck(mIndex, gIndex)"></checkbox>
						<image :src="item.goodIcon" class="goods-img"></image>
						<view class="goods-info">
							<view class="goods-name text-cut">{{ item.goodName }}</view>
							<view class="goods-spec text-gray">{{ item.specsText || '默认规格' }}</view>
							<view class="goods-price-row">
								<text class="price text-red text-bold">¥{{ item.price.toFixed(2) }}</text>
							</view>
						</view>
						<view class="goods-quantity">
							<text>x{{ item.quantity }}</text>
						</view>
						
						<!-- 长按显示的删除按钮遮罩层 -->
						<view class="delete-overlay" v-if="longPressItem.mIndex === mIndex && longPressItem.gIndex === gIndex">
							<view class="delete-btn" @click="handleDelete(mIndex, gIndex)">
								<text class="cuIcon-delete text-white"></text>
								<text class="text-white">删除</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部结算栏 -->
		<view class="cu-bar bg-white tabbar shop-foot" v-if="merchantCarts && merchantCarts.length > 0">
			<view class="action check-action" @tap="handleAllCheck">
				<view class="custom-checkbox" :class="{'checked': isAllChecked}">
					<text class="cuIcon-check text-white" v-if="isAllChecked"></text>
				</view>
				<text class="margin-left-sm">全选</text>
			</view>
			
			<view class="action text-xl">
				<text class="text-grey">合计：</text>
				<text class="text-red text-bold">¥{{ totalPrice.toFixed(2) }}</text>
			</view>
			
			<view class="bg-red submit">
				结算
			</view>
		</view>

		<!-- 全屏遮罩，点击任意位置取消长按状态 -->
		<view class="fullscreen-overlay" v-if="isLongPressed" @click="cancelLongPress"></view>
	</view>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { get, post } from '@/utils/request.js';

const merchantCarts = ref([]);

// 长按相关状态
const isLongPressed = ref(false);
const longPressItem = ref({
	mIndex: -1,
	gIndex: -1
});

// --- 计算属性 ---

// 计算总价
const totalPrice = computed(() => {
	let total = 0;
	merchantCarts.value.forEach(merchant => {
		merchant.cartItems.forEach(item => {
			if (item.checked) {
				total += item.price * item.quantity;
			}
		});
	});
	return total;
});

// 计算是否全选
const isAllChecked = computed(() => {
	if (!merchantCarts.value || merchantCarts.value.length === 0) return false;
	
	// 检查每个商家中的每个商品是否都被选中
	for (const merchant of merchantCarts.value) {
		for (const item of merchant.cartItems) {
			if (!item.checked) {
				return false;
			}
		}
	}
	return true;
});


// --- 方法 ---

const fetchCartData = async () => {
	const storedUser = uni.getStorageSync('user');
	if (!storedUser) {
		uni.showToast({ title: '请先登录', icon: 'none' });
		merchantCarts.value = [];
		return;
	}
	
	try {
		const userData = JSON.parse(storedUser);
		const userId = userData.userId;

		if (!userId) return;

		uni.showLoading({ title: '加载中...' });
		const res = await get(`/cart/findByUserId?userId=${userId}`);
		uni.hideLoading();

		if (res.data && res.data.code === 200) {
			const cartsFromServer = res.data.msg || [];
			// **重要**: 为数据添加前端选择状态
			cartsFromServer.forEach(merchant => {
				merchant.checked = false;
				if (merchant.cartItems) {
					merchant.cartItems.forEach(item => {
						item.checked = false;
					});
				}
			});
			merchantCarts.value = cartsFromServer;
		} else {
			uni.showToast({ title: res.data?.msg || '加载购物车失败', icon: 'none' });
		}
	} catch (error) {
		uni.hideLoading();
		console.error("获取购物车数据失败:", error);
	}
};

// 切换商品选择
const toggleGoodsCheck = (mIndex, gIndex) => {
	// 使用新数组方式更新，确保响应式捕获到变化
	const newMerchantCarts = [...merchantCarts.value];
	const merchant = {...newMerchantCarts[mIndex]};
	const newCartItems = [...merchant.cartItems];
	
	// 切换当前商品的选中状态
	newCartItems[gIndex] = {...newCartItems[gIndex], checked: !newCartItems[gIndex].checked};
	
	// 判断该商家的所有商品是否都被选中
	const allItemsChecked = newCartItems.every(item => item.checked);
	merchant.cartItems = newCartItems;
	merchant.checked = allItemsChecked;
	
	newMerchantCarts[mIndex] = merchant;
	merchantCarts.value = newMerchantCarts;
};

// 切换店铺选择
const toggleShopCheck = (mIndex) => {
	// 使用新数组方式更新，确保响应式捕获到变化
	const newMerchantCarts = [...merchantCarts.value];
	const merchant = {...newMerchantCarts[mIndex]};
	const newCheckState = !merchant.checked;
	
	// 更新商家及其所有商品的选中状态
	const newCartItems = merchant.cartItems.map(item => ({...item, checked: newCheckState}));
	merchant.cartItems = newCartItems;
	merchant.checked = newCheckState;
	
	newMerchantCarts[mIndex] = merchant;
	merchantCarts.value = newMerchantCarts;
};

// 切换全选（直接给底部按钮使用）
const handleAllCheck = () => {
	console.log('全选按钮被点击');
	
	// 手动触发提示，让用户知道按钮被点击了
	uni.showToast({
		title: '正在设置全选状态',
		icon: 'none',
		duration: 1000
	});
	
	// 获取当前全选状态的反值
	const newCheckState = !isAllChecked.value;
	console.log('新的选中状态应该是:', newCheckState);
	
	// 创建一个全新的购物车数组
	const newMerchantCarts = merchantCarts.value.map(merchant => {
		// 为每个商家创建一个新对象
		const newMerchant = { ...merchant, checked: newCheckState };
		
		// 为每个商品创建一个新对象，并设置选中状态
		newMerchant.cartItems = merchant.cartItems.map(item => {
			return { ...item, checked: newCheckState };
		});
		
		return newMerchant;
	});
	
	// 完全替换购物车数组
	merchantCarts.value = newMerchantCarts;
	
	// 打印一下商家和商品的选中状态，帮助调试
	console.log('更新后的购物车状态:', 
		merchantCarts.value.map(m => ({
			merchantId: m.merchantId,
			checked: m.checked,
			items: m.cartItems.map(i => i.checked)
		}))
	);
	
	// 强制重新计算一下全选状态
	console.log('isAllChecked 现在是:', isAllChecked.value);
};

// 长按商品处理
const handleLongPress = (mIndex, gIndex) => {
	isLongPressed.value = true;
	longPressItem.value = { mIndex, gIndex };
};

// 取消长按状态
const cancelLongPress = () => {
	isLongPressed.value = false;
	longPressItem.value = { mIndex: -1, gIndex: -1 };
};

// 删除商品处理
const handleDelete = async (mIndex, gIndex) => {
	try {
		// 获取要删除的商品信息
		const merchant = merchantCarts.value[mIndex];
		const item = merchant.cartItems[gIndex];
		const userId = JSON.parse(uni.getStorageSync('user')).userId;
		console.log("信息",userId, item.goodId, merchant.merchantId)
		
		// 这里应该调用后端删除购物车商品的接口
		await get(`/cart/deleteToMySQL?userId=${userId}&goodId=${item.goodId}&merchantId=${merchant.merchantId}`);
		
		// 先简单模拟一下删除成功
		uni.showLoading({ title: '删除中...' });
		
		// 等待一会儿模拟网络请求
		setTimeout(() => {
			// 更新本地数据（删除该商品）
			const newMerchantCarts = [...merchantCarts.value];
			const newMerchant = {...newMerchantCarts[mIndex]};
			
			// 从商品列表中移除该商品
			newMerchant.cartItems = newMerchant.cartItems.filter((_, idx) => idx !== gIndex);
			
			// 如果该商家已经没有商品了，则从商家列表中移除该商家
			if (newMerchant.cartItems.length === 0) {
				newMerchantCarts.splice(mIndex, 1);
			} else {
				newMerchantCarts[mIndex] = newMerchant;
			}
			
			merchantCarts.value = newMerchantCarts;
			cancelLongPress(); // 关闭删除遮罩
			
			uni.hideLoading();
			uni.showToast({ title: '删除成功', icon: 'success' });
		}, 500);
		
	} catch (error) {
		uni.hideLoading();
		console.error("删除商品失败:", error);
		uni.showToast({ title: '删除失败', icon: 'none' });
	}
};

const goToHome = () => {
	uni.switchTab({
		url: '/pages/index/HomePage'
	});
};

// 使用 onShow，这样每次切换到该页面都会自动刷新数据
onShow(() => {
	fetchCartData();
});
</script>

<style scoped>
.page-container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}
.empty-cart {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding-top: 200rpx;
}
.cart-list {
	padding: 20rpx;
}
.merchant-card {
	background-color: #ffffff;
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
}
.merchant-header {
	display: flex;
	align-items: center;
	padding-bottom: 20rpx;
}
.goods-list {
	display: flex;
	flex-direction: column;
}
.goods-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-top: 1rpx solid #f1f1f1;
	position: relative; /* 为删除按钮定位做准备 */
}
.goods-img {
	width: 160rpx;
	height: 160rpx;
	border-radius: 8rpx;
	margin: 0 20rpx;
	flex-shrink: 0;
}
.goods-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	height: 160rpx;
	overflow: hidden;
}
.goods-name {
	font-size: 28rpx;
	font-weight: bold;
}
.goods-spec {
	font-size: 24rpx;
	color: #888;
}
.goods-price-row {
	display: flex;
	align-items: baseline;
}
.price {
	font-size: 32rpx;
}
.goods-quantity {
	padding: 0 20rpx;
	font-size: 28rpx;
	color: #888;
}

/* 删除按钮遮罩层 */
.delete-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.6);
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 8rpx;
	z-index: 10;
}
.delete-btn {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	padding: 20rpx;
}
.delete-btn .cuIcon-delete {
	font-size: 50rpx;
	margin-bottom: 10rpx;
}

/* 全屏遮罩，点击任意位置取消长按状态 */
.fullscreen-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 5;
}

/* 底部结算栏 */
.shop-foot {
	position: fixed;
	bottom: var(--window-bottom);
	width: 100%;
	box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
	z-index: 9;
}
.shop-foot .action {
	display: flex;
	align-items: center;
}
checkbox {
	transform: scale(0.8);
}

/* 新增：一个可见的全选按钮 */
.big-select-all-btn {
	position: fixed;
	bottom: 150rpx;
	right: 30rpx;
	background-color: rgba(0, 0, 0, 0.7);
	color: white;
	padding: 15rpx 30rpx;
	border-radius: 50rpx;
	z-index: 100;
	font-size: 26rpx;
}

/* 新增：自定义复选框样式 */
.custom-checkbox {
	width: 40rpx;
	height: 40rpx;
	border: 2rpx solid #ccc;
	border-radius: 50%;
	display: flex;
	justify-content: center;
	align-items: center;
}
.custom-checkbox.checked {
	background-color: #ff0000;
	border-color: #ff0000;
}

/* 增大点击区域 */
.check-action {
	padding: 20rpx;
}
</style>